package com.ksd.web.controller.system;

import java.io.*;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import com.ksd.api.controller.checkVersion;
import com.ksd.common.annotation.Log;
import com.ksd.common.config.PlayControlConfig;
import com.ksd.common.core.controller.BaseController;
import com.ksd.common.core.domain.AjaxResult;
import com.ksd.common.enums.BusinessType;
import com.ksd.common.utils.StringUtils;
import com.ksd.system.domain.SysBoard;
import com.ksd.system.service.ISysBoardService;
import com.ksd.system.service.ISysOperLogService;
import com.ksd.web.controller.networkBean.*;
import com.ksd.web.controller.service.AsyncService;
import com.ksd.web.controller.service.SendChannelService;
import com.ksd.web.controller.tool.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ksd.system.domain.SysNetwork;
import com.ksd.system.service.ISysNetworkService;
import org.yaml.snakeyaml.Yaml;

import static com.github.pagehelper.page.PageMethod.offsetPage;
import static com.ksd.common.utils.PageUtils.startPage;

/**
 * 网络配置Controller
 * 
 * @author y.wu
 * @date 2025-01-08
 */
@RestController
@RequestMapping("/system/network")
public class SysNetworkController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(checkVersion.class);
    @Autowired
    private ISysNetworkService sysNetworkService;
    @Autowired
    private ISysOperLogService sysOperLogService;
    @Autowired
    private SendChannelService sendChannelService;
    @Autowired
    private ISysBoardService sysBoardService;
    @Autowired
    private AsyncService asyncService;

    @PreAuthorize("@ss.hasPermi('system:network:list')")
    @GetMapping("/sqlList")
    public AjaxResult sqlList(SysNetwork sysNetwork) {
        SysNetworkUtil sysNetworkUtil = new SysNetworkUtil();
        SysNetwork sysNetwork1 = sysNetworkService.selectSysNetworkById(sysNetwork.defaultId);
        SysNetwork sysNetwork2 = sysNetworkService.selectSysNetworkById(sysNetwork.eth1_id);
        SysNetwork sysNetwork3 = sysNetworkService.selectSysNetworkById(sysNetwork.eth2_id);

        String subnetMask = sysNetwork1.getSubnetMask();
        if (subnetMask.indexOf(".") == -1){
            String mask = SubnetMaskConversion.convertCidrToDottedDecimal(Integer.valueOf(subnetMask));
            sysNetwork1.setSubnetMask(mask);
        }
        String subnetMask2 = sysNetwork2.getSubnetMask();
        if (subnetMask2.indexOf(".") == -1){
            String mask2 = SubnetMaskConversion.convertCidrToDottedDecimal(Integer.valueOf(subnetMask2));
            sysNetwork2.setSubnetMask(mask2);
        }
        String subnetMask3 = sysNetwork3.getSubnetMask();
        if (subnetMask3.indexOf(".") == -1){
            String mask3 = SubnetMaskConversion.convertCidrToDottedDecimal(Integer.valueOf(subnetMask3));
            sysNetwork3.setSubnetMask(mask3);
        }

        sysNetworkUtil.setSysNetwork(sysNetwork1);
        sysNetworkUtil.setSysNetwork1(sysNetwork2);
        sysNetworkUtil.setSysNetwork2(sysNetwork3);
        return AjaxResult.success(sysNetworkUtil);
    }


    /**
     * 查询网络配置列表
     */
    @PreAuthorize("@ss.hasPermi('system:network:list')")
    @GetMapping("/list")
    // public TableDataInfo list(SysNetwork sysNetwork)
    public AjaxResult list(SysNetwork sysNetwork) {
        String os = System.getProperty("os.name").toLowerCase();
        SysNetworkUtil sysNetworkUtil = new SysNetworkUtil();
        System.out.println("os:" + os);
        if (os.startsWith("win")) {
            SysNetwork sysNetwork1 = sysNetworkService.selectSysNetworkById(sysNetwork.defaultId);
            String subnetMask = sysNetwork1.getSubnetMask();
            if (subnetMask.indexOf(".") == -1){
                String mask = SubnetMaskConversion.convertCidrToDottedDecimal(Integer.valueOf(subnetMask));
                sysNetwork1.setSubnetMask(mask);
            }
            sysNetworkUtil.setPingNetworkChange(false);
            sysNetworkUtil.setSysNetwork(sysNetwork1);
        } else {
            String networkX86Path = PlayControlConfig.getNetworkX86Path();
            Map<String, String> stringStringMap = readConfig(networkX86Path);
            String ip = stringStringMap.get("ip");
            String netmask = stringStringMap.get("netmask");
            String gateway = stringStringMap.get("gateway");
            SysNetwork sysNetwork1 = sysNetworkService.selectSysNetworkById(sysNetwork.defaultId);
            if (netmask.indexOf(".") == -1){
                netmask = SubnetMaskConversion.convertCidrToDottedDecimal(Integer.valueOf(netmask));
            }
            sysNetwork1.setIp(ip);
            sysNetwork1.setGateway(gateway);
            sysNetwork1.setSubnetMask(netmask);
            sysNetworkService.updateSysNetwork(sysNetwork1);

            sysNetworkUtil.setPingNetworkChange(true);
            sysNetworkUtil.setSysNetwork(sysNetwork1);
        }

        //获取直播网卡1和直播板卡2的网络地址
        SysNetwork sysNetwork2 = sysNetworkService.selectSysNetworkById(SysNetwork.eth1_id);
        SysNetwork sqlNetwork2 = sysNetworkService.selectSysNetworkById(SysNetwork.eth1_id);
        SysBoard sysBoard1 = sysBoardService.selectSysBoardById(SysBoard.boardId1);
        String url1 = sysBoard1.getUrl();
        boolean changeFlag2 = pingIP(sysNetwork2.getIp());
        if (changeFlag2){
            try {
                sysNetwork2 = sendChannelService.getIpMode1(url1, sysNetwork2);
                if (StringUtils.isNull(sysNetwork2)){
                    logger.info("获取数据位空");
                    sysNetworkUtil.setPingNetworkChange1(false);
                    sysNetworkUtil.setSysNetwork1(sqlNetwork2);
                }else{
                    logger.info("数据不为空");
                    sysNetworkUtil.setPingNetworkChange1(true);
                    sysNetwork2 = sendChannelService.getMethod2(url1, sysNetwork2);
                    sysNetwork2 = sendChannelService.getMethod3(url1, sysNetwork2);
                    sysNetwork2 = sendChannelService.rgextRoute(url1, sysNetwork2);
                    String subnetMask2 = sysNetwork2.getSubnetMask();
                    if (subnetMask2.indexOf(".") == -1){
                        subnetMask2 = SubnetMaskConversion.convertCidrToDottedDecimal(Integer.valueOf(subnetMask2));
                    }
                    sysNetwork2.setSubnetMask(subnetMask2);
                    sysNetworkUtil.setSysNetwork1(sysNetwork2);
                    sysNetworkService.updateSysNetwork(sysNetwork2);
                }
            } catch (Exception e) {
                sysNetworkUtil.setPingNetworkChange1(false);
                sysNetworkUtil.setSysNetwork1(sqlNetwork2);
            }
        }else{
            sysNetworkUtil.setPingNetworkChange1(false);
            sysNetworkUtil.setSysNetwork1(sysNetwork2);
        }


        SysNetwork sysNetwork3 = sysNetworkService.selectSysNetworkById(SysNetwork.eth2_id);
        SysNetwork sqlNetwork3 = sysNetworkService.selectSysNetworkById(SysNetwork.eth2_id);
        SysBoard sysBoard2 = sysBoardService.selectSysBoardById(SysBoard.boardId2);
        String url2 = sysBoard2.getUrl();
        boolean changeFlag3 = pingIP(sysNetwork3.getIp());
        if (changeFlag3){
            try {
                sysNetwork3 = sendChannelService.getIpMode1(url2, sysNetwork3);
                if (StringUtils.isNull(sysNetwork3)){
                    sysNetworkUtil.setPingNetworkChange2(false);
                    sysNetworkUtil.setSysNetwork2(sqlNetwork3);
                }else{
                    sysNetwork3 = sendChannelService.getMethod2(url2, sysNetwork3);
                    sysNetwork3 = sendChannelService.getMethod3(url2, sysNetwork3);
                    sysNetwork3 = sendChannelService.rgextRoute(url2, sysNetwork3);
                    String subnetMask3 = sysNetwork3.getSubnetMask();
                    if (subnetMask3.indexOf(".") == -1){
                        subnetMask3 = SubnetMaskConversion.convertCidrToDottedDecimal(Integer.valueOf(subnetMask3));
                    }
                    sysNetwork3.setSubnetMask(subnetMask3);

                    sysNetworkUtil.setPingNetworkChange2(true);
                    sysNetworkUtil.setSysNetwork2(sysNetwork3);
                    sysNetworkService.updateSysNetwork(sysNetwork3);
                }
            } catch (Exception e) {
                sysNetworkUtil.setPingNetworkChange2(false);
                sysNetworkUtil.setSysNetwork2(sqlNetwork3);
            }

        }else{
            sysNetworkUtil.setPingNetworkChange2(false);
            sysNetworkUtil.setSysNetwork2(sqlNetwork3);
        }
        return success(sysNetworkUtil);
    }

    /**
     * 获取网络配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:network:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(sysNetworkService.selectSysNetworkById(id));
    }

    /**
     * 修改网络配置
     */
    @PreAuthorize("@ss.hasPermi('system:network:edit')")
    @Log(title = "网络配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysNetwork sysNetwork, HttpServletRequest request) {


        Long id = sysNetwork.getId();
        logger.info("网络配置ID:"+id);
        SysNetwork sysNetworkSql = sysNetworkService.selectSysNetworkById(id);
        String gateway = sysNetwork.getGateway();
        String ip = sysNetwork.getIp();
        String mac = sysNetwork.getMac();
        String subnetMask = sysNetwork.getSubnetMask();

        String os = System.getProperty("os.name").toLowerCase();
        if (id == 1) {
            if (os.startsWith("win")) {
                return success();
            }else {
                logger.info("修改主板服务器的网络配置");
                String linuxNetworkPath = PlayControlConfig.getNetworkX86Path();
                //修改服务器上的网络文件地址
                modifyConfig(linuxNetworkPath, sysNetwork.getIp(), sysNetwork.getSubnetMask(), sysNetwork.getGateway());

                SysBoard sysBoard = sysBoardService.selectSysBoardById(SysBoard.serviceFileId);
                String url = sysBoard.getUrl();
                int indexStart = url.indexOf(":");
                int indexEnd = url.lastIndexOf(":");
                String substringStart = url.substring(0, indexStart + 3);
                String substringEnd = url.substring(indexEnd);
                logger.info("substringStart:" + substringStart);
                logger.info("substringEnd:" + substringEnd);
                String newIp = substringStart + sysNetwork.getIp() + substringEnd;
                sysBoard.setUrl(newIp);
                sysBoardService.updateSysBoard(sysBoard);
                sysNetworkService.updateSysNetwork(sysNetwork);
                logger.info("更新主控板配置成功.原MAC地址:" + sysNetworkSql.getMac() + ",更新为:" + mac + " ,原IP地址:" + sysNetworkSql.getIp() + ",更新为:" + ip + ",原子网掩码:" + sysNetworkSql.getSubnetMask() + "更新为:" + subnetMask + " ,原网关地址:" + sysNetworkSql.getGateway() + ",更新后的网关地址:" + gateway);
                sysOperLogService.insertOperlogSuccess("更新主控板配置成功.原MAC地址:" + sysNetworkSql.getMac() + ",更新为:" + mac + " ,原IP地址:" + sysNetworkSql.getIp() + ",更新为:" + ip + ",原子网掩码:" + sysNetworkSql.getSubnetMask() + "更新为:" + subnetMask + " ,原网关地址:" + sysNetworkSql.getGateway() + ",更新后的网关地址:" + gateway);

                //重启网络服务
                asyncService.asyncNetworkConfig();
//                ContOsTool.rebootService();

                return success("配置已更新，网络将自动重启");
            }
        } else if (id == 2) {
            SysBoard sysBoard = sysBoardService.selectSysBoardById(SysBoard.boardId1);
            AjaxResult ajaxResult = setNetworkConfig(sysNetwork, sysBoard);
            if (ajaxResult.isSuccess()){
                sysOperLogService.insertOperlogSuccess("更新直播板卡1配置成功.原MAC地址:" + sysNetworkSql.getMac() + ",更新为:" + mac + " ,原IP地址:" + sysNetworkSql.getIp() + ",更新为:" + ip + ",原子网掩码:" + sysNetworkSql.getSubnetMask() + "更新为:" + subnetMask + " ,原网关地址:" + sysNetworkSql.getGateway() + ",更新后的网关地址:" + gateway);
            }else{
                sysOperLogService.insertOperlogError("更新直播板卡1配置失败.原MAC地址:" + sysNetworkSql.getMac() + ",更新为:" + mac + " ,原IP地址:" + sysNetworkSql.getIp() + ",更新为:" + ip + ",原子网掩码:" + sysNetworkSql.getSubnetMask() + "更新为:" + subnetMask + " ,原网关地址:" + sysNetworkSql.getGateway() + ",更新后的网关地址:" + gateway);
            }
            return ajaxResult;

        } else if (id == 3) {
            SysBoard sysBoard = sysBoardService.selectSysBoardById(SysBoard.boardId2);
            AjaxResult ajaxResult = setNetworkConfig(sysNetwork, sysBoard);
            if (ajaxResult.isSuccess()){
                sysOperLogService.insertOperlogSuccess("更新直播板卡2配置成功.原MAC地址:" + sysNetworkSql.getMac() + ",更新为:" + mac + " ,原IP地址:" + sysNetworkSql.getIp() + ",更新为:" + ip + ",原子网掩码:" + sysNetworkSql.getSubnetMask() + "更新为:" + subnetMask + " ,原网关地址:" + sysNetworkSql.getGateway() + ",更新后的网关地址:" + gateway);
            }else{
                sysOperLogService.insertOperlogError("更新直播板卡2配置失败.原MAC地址:" + sysNetworkSql.getMac() + ",更新为:" + mac + " ,原IP地址:" + sysNetworkSql.getIp() + ",更新为:" + ip + ",原子网掩码:" + sysNetworkSql.getSubnetMask() + "更新为:" + subnetMask + " ,原网关地址:" + sysNetworkSql.getGateway() + ",更新后的网关地址:" + gateway);
            }
            return ajaxResult;
        }
        return error();
    }

    public AjaxResult setNetworkConfig(SysNetwork sysNetwork, SysBoard sysBoard) {
        String ip1 = sysNetwork.getIp();
        String subnetMask1 = sysNetwork.getSubnetMask();
        String gateway1 = sysNetwork.getGateway();
        int netlen = SubnetMaskConversion.convertToCidr(subnetMask1);

        BatchCmdIp cmdIp = new BatchCmdIp();
        cmdIp.setIpaddr(ip1);
        cmdIp.setNetlen(netlen);
        cmdIp.setVer(4);

        String url = sysBoard.getUrl();
        boolean flag = sendChannelService.setNetworkConfig(url, cmdIp, gateway1);
        if (flag){
            //修改IP地址后,不解析接口返回值==>判断是否能ping通新的IP
            boolean changeFlag = pingIP(ip1);
            if (changeFlag) {
                int indexStart = url.lastIndexOf(":");
                int indexEnd = url.lastIndexOf("/");
                String substringStart = url.substring(0, indexStart+3);
                String substringEnd = url.substring(indexEnd);
                logger.info("=========substringStart:"+substringStart);
                logger.info("==============substringEnd:"+substringEnd);

                String newIp = substringStart+cmdIp.getIpaddr()+substringEnd;

                sysBoard.setUrl(newIp);
                sysBoardService.updateSysBoard(sysBoard);
                sysNetworkService.updateSysNetwork(sysNetwork);
                return success();
            }else{
                return error();
            }
        }else{
            return error();
        }


//        sysOperLogService.insertOperlogSuccess("修改网络配置接口.请求地址: "+url+",响应数据:"+response);
//        if (StringUtils.isEmpty(response)){
//            sysOperLogService.insertOperlogApiError("修改网络配置接口.请求地址: "+url+",响应超时,请联系管理员检查接口服务或稍后重试");
//            return error("频道输出设置接口响应超时,请联系管理员检查接口服务或稍后重试");
//        }
//        ObjectMapper mapperPage = new ObjectMapper();
//        BatchCmdResponse batchCmdResponse = null;
//        try {
//            ObjectMapper objectMapper = new ObjectMapper();
//            // 将 JSON 字符串解析为 JsonNode 对象
//            JsonNode rootNode = objectMapper.readTree(response);
//            // 获取 status 节点的值
//            int statusInt = rootNode.get("status").asInt();
//            if (statusInt != 0) {
//                sysOperLogService.insertOperlogApiError("修改网络配置接口.请求地址: "+url+",响应状态失败，请联系管理员检查接口服务或稍后重试");
//                return error("修改网络配置接口响应状态失败，请联系管理员检查接口服务或稍后重试");
//            }else{
//                //更新网络配置
//                int indexStart = url.lastIndexOf(":");
//                int indexEnd = url.lastIndexOf("/");
//                String substringStart = url.substring(0, indexStart+3);
//                String substringEnd = url.substring(indexEnd);
//                System.out.println("substringStart:"+substringStart);
//                System.out.println("substringEnd:"+substringEnd);
//
//                String newIp = substringStart+cmdIp.getIpaddr()+substringEnd;
//
//                sysBoard.setUrl(newIp);
//                sysBoardService.updateSysBoard(sysBoard);
//                return success();
//            }
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException(e);
//        }
    }

    public static boolean pingIP(String ipAddress) {
        int timeout = 3000; // 超时时间，单位为毫秒
        try {
            // 根据 IP 地址创建 InetAddress 对象
            InetAddress inet = InetAddress.getByName(ipAddress);
            // 尝试与指定 IP 地址建立连接，超时时间由 timeout 参数指定
            return inet.isReachable(timeout);
        } catch (IOException e) {
            // 处理可能出现的输入输出异常
            System.err.println("An error occurred while pinging " + ipAddress + ": " + e.getMessage());
            return false;
        }
    }


    /**
     * 删除网络配置
     */
    @PreAuthorize("@ss.hasPermi('system:network:remove')")
    @Log(title = "网络配置", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysNetworkService.deleteSysNetworkByIds(ids));
    }


    public static Map<String, String> readConfig(String configFilePath) {
        Map<String, String> result = new HashMap<>();
        logger.info("网络配置文件路径:"+configFilePath);
        File file = new File(configFilePath);

        try{
            if (file.exists()){
                logger.info("网络配置文件存在");
                InputStream inputStream = new FileInputStream(file);

                Yaml yaml = new Yaml();
                Map<String, Object> yamlMap = yaml.load(inputStream);

                // 获取ethernets部分
                Map<String, Object> network = (Map<String, Object>) yamlMap.get("network");
                Map<String, Object> ethernets = (Map<String, Object>) network.get("ethernets");
                Map<String, Object> NM = (Map<String, Object>) ethernets.get("NM-1619e8e6-69af-32d9-a7ef-bac039c6e9fc");
                Map<String, Object> networkmanager = (Map<String, Object>) NM.get("networkmanager");
                Map<String, Object> passthrough = (Map<String, Object>) networkmanager.get("passthrough");
                List<String> addresses = (List<String>) NM.get("addresses");

                // 获取IP地址
                if (!addresses.isEmpty()) {
                    String[] ipAndMask = addresses.get(0).split("/");
                    logger.info(ipAndMask[0]+"************"+ipAndMask[1]);
                    result.put("ip", ipAndMask[0]);
                    result.put("netmask", ipAndMask[1]);
                }

                // 获取网关（从ipv4.address1提取，根据配置文件实际情况调整）
                String ipv4Address1 = (String) passthrough.get("ipv4.address1");
                if (ipv4Address1 != null) {
                    String[] parts = ipv4Address1.split(",");
                    if (parts.length > 1) {
                        logger.info(parts[0]+"================="+parts[1]);
                        result.put("gateway", parts[1]);
                    }
                }
            }else{
                logger.info("网络文件地址不存在:"+configFilePath);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        String networkX86Path = "/etc/netplan/90-NM-1619e8e6-69af-32d9-a7ef-bac039c6e9fc.yaml";
        int i = networkX86Path.indexOf("-");
        int i1 = networkX86Path.lastIndexOf(".");
        String substring = networkX86Path.substring(i + 1,i1);
        System.out.println(substring);
    }
    public static void modifyConfig(String configFilePath, String newIp, String newNetmask, String newGateway) {
        try {
            Yaml yaml = new Yaml();
            Map<String, Object> yamlMap = yaml.load(new java.io.FileReader(configFilePath));

            // 获取ethernets部分
            Map<String, Object> network = (Map<String, Object>) yamlMap.get("network");
            Map<String, Object> ethernets = (Map<String, Object>) network.get("ethernets");
            String networkX86Path = PlayControlConfig.getNetworkX86Path();
            int i = networkX86Path.indexOf("-");
            int i1 = networkX86Path.lastIndexOf(".");
            String substring = networkX86Path.substring(i + 1,i1);

            Map<String, Object> NM = (Map<String, Object>) ethernets.get("NM-1619e8e6-69af-32d9-a7ef-bac039c6e9fc");
//            Map<String, Object> NM = (Map<String, Object>) ethernets.get(substring);
            Map<String, Object> networkmanager = (Map<String, Object>) NM.get("networkmanager");
            Map<String, Object> passthrough = (Map<String, Object>) networkmanager.get("passthrough");
            List<String> addresses = (List<String>) NM.get("addresses");
            Map<String, Object> nameservers = (Map<String, Object>) NM.get("nameservers");
            List<String> serversAddresses = (List<String>)nameservers.get("addresses");

            int maskInt = SubnetMaskConversion.convertToCidr(newNetmask);
            logger.info("maskInt:"+maskInt);
            // 修改IP地址和子网掩码
            if (!addresses.isEmpty()) {
                addresses.set(0, newIp + "/" + maskInt);
            }
            
            if (!serversAddresses.isEmpty()) {
                logger.info("serversAddresses:"+serversAddresses.size()+"==========="+serversAddresses.toString());
                String s1 = serversAddresses.get(0);
                String s2 = serversAddresses.get(1);
                if (StringUtils.isNotEmpty(s1)){
                    logger.info("serversAddresses s1:"+s1);
                }
                if (StringUtils.isNotEmpty(s2)){
                    logger.info("serversAddresses s2:"+s2);
                }
                serversAddresses.set(0,newGateway);
            }

            // 修改网关（从ipv4.address1修改，根据实际调整）
            String ipv4Address1Key = "ipv4.address1";
            String ipv4Address1 = (String) passthrough.get(ipv4Address1Key);
            logger.info("ipv4Address1:========================"+ipv4Address1);
            if (ipv4Address1 != null){
                String[] ips = ipv4Address1.split("/");
                if (ips.length > 0) {
                    ips[0] = newIp;
                    logger.info("ips=================="+ips[0]+"=============="+ips.length);
                    passthrough.put(ipv4Address1Key, String.join("/", ips));
                }
            }
            String ipv4Address1Value = newIp+"/"+maskInt+","+newGateway;
            logger.info("重新修改后的数据ipv4Address1Value:"+ipv4Address1Value);
            passthrough.put(ipv4Address1Key, ipv4Address1Value);



            // 将修改后的内容写回文件
            try (FileWriter writer = new FileWriter(configFilePath)) {
                yaml.dump(yamlMap, writer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
